#include "Motor.h"


extern Timer_typeDef timer;
extern PID_Mode current_pid_mode;


///*	 配置PWM参数：
//		 * - PWM_0_INST: 使用定时器 TIMG7 作为 PWM 生成器
//		 * - 500: 占空比设置为 500
//		 * - GPIO_PWM_0_C1_IDX: 使用定时器模块的捕获/比较通道 1
//		 */
//		DL_TimerG_setCaptureCompareValue(PWM_0_INST, 950, GPIO_PWM_0_C1_IDX);
void MOTOR_SetCompare(uint32_t CHANNEL11,uint32_t CHANNEL12,uint32_t CHANNEL21,uint32_t CHANNEL22)
{
	DL_TimerG_setCaptureCompareValue(PWM_1_INST, CHANNEL11, GPIO_PWM_1_C0_IDX);
	DL_TimerG_setCaptureCompareValue(PWM_3_INST, CHANNEL12, GPIO_PWM_3_C0_IDX);
	DL_TimerG_setCaptureCompareValue(PWM_2_INST, CHANNEL21, GPIO_PWM_2_C0_IDX);
	DL_TimerG_setCaptureCompareValue(PWM_2_INST, CHANNEL22, GPIO_PWM_2_C1_IDX);
}


//give the speed disregarded positive or negative
void MOTOR_GiveSpeed(int Speed1,int Speed2)		
{
	if(Speed2<0 && Speed2>-9999)
	{
		DL_TimerG_setCaptureCompareValue(PWM_1_INST, 0, GPIO_PWM_1_C0_IDX);
		DL_TimerG_setCaptureCompareValue(PWM_3_INST, -Speed2, GPIO_PWM_3_C0_IDX);
	}
	else if(Speed2>=0 && Speed2<9999)
	{
		DL_TimerG_setCaptureCompareValue(PWM_1_INST, Speed2, GPIO_PWM_1_C0_IDX);
		DL_TimerG_setCaptureCompareValue(PWM_3_INST, 0, GPIO_PWM_3_C0_IDX);
	}
	else if(Speed2 <= -9999)
	{
		DL_TimerG_setCaptureCompareValue(PWM_1_INST, 0, GPIO_PWM_1_C0_IDX);
		DL_TimerG_setCaptureCompareValue(PWM_3_INST, 9999, GPIO_PWM_3_C0_IDX);
	}
	else if(Speed2 >= 9999)
	{
		DL_TimerG_setCaptureCompareValue(PWM_1_INST, 9999, GPIO_PWM_1_C0_IDX);
		DL_TimerG_setCaptureCompareValue(PWM_3_INST, 0, GPIO_PWM_3_C0_IDX);
	}
	
	if(Speed1<0 && Speed1>-9999)
	{
		DL_TimerG_setCaptureCompareValue(PWM_2_INST, 0, GPIO_PWM_2_C0_IDX);
		DL_TimerG_setCaptureCompareValue(PWM_2_INST, -Speed1, GPIO_PWM_2_C1_IDX);
	}
	else if(Speed1>=0 && Speed1<9999)
	{
		DL_TimerG_setCaptureCompareValue(PWM_2_INST, Speed1, GPIO_PWM_2_C0_IDX);
		DL_TimerG_setCaptureCompareValue(PWM_2_INST, 0, GPIO_PWM_2_C1_IDX);
	}
	else if(Speed1 >= 9999)
	{
		DL_TimerG_setCaptureCompareValue(PWM_2_INST, 9999, GPIO_PWM_2_C0_IDX);
		DL_TimerG_setCaptureCompareValue(PWM_2_INST, 0, GPIO_PWM_2_C1_IDX);
	}
	else if(Speed1 <= -9999)
	{
		DL_TimerG_setCaptureCompareValue(PWM_2_INST, 0, GPIO_PWM_2_C0_IDX);
		DL_TimerG_setCaptureCompareValue(PWM_2_INST, 9999, GPIO_PWM_2_C1_IDX);
	}
}


void MOTOR_Stop(void)
{
	timer.state = STATE_OPEN_LOOP;
	current_pid_mode = OPEN_LOOP;
	timer.mpu_flag = 0;
	MOTOR_GiveSpeed(0,0);
}